package com.sky.service.impl;

import com.sky.dto.ReportDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.vo.TurnoverReportVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    OrderMapper orderMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1. 准备2个需要封装的数据集合
        ArrayList<LocalDate> dateList = new ArrayList<>();
        ArrayList<Object> turnoverList = new ArrayList<>();

        //2. dateList填充数据
        dateList.add(begin);
        while (!begin.equals(end)){
            //注意：需要给begin重新赋值，否则begin没有变化
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //3. 给每天的营业额集合填充数据
        //3.1 查询每天的营业额
        List<ReportDTO> reportDTOList = orderMapper.turnoverStatistics(dateList.get(0), end, Orders.COMPLETED);
        //3.2 遍历日期
        for (LocalDate time : dateList) {
            //3.3 从查询结果中找，看当天有没有营业额
            Optional<ReportDTO> optional = reportDTOList.stream().filter(reportDTO -> {
                return reportDTO.getTime().equals(time); //boolean
            }).findFirst();
            //3.4 有：turnoverList.add(total)
            if(optional.isPresent()){
                turnoverList.add(optional.get().getTotal());
            }else {
                //3.5 没有：turnoverList.add(0)
                turnoverList.add(0);
            }
        }

        //StringUtils.join(dateList, ",");
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return vo;
    }
}
